package com.example.munidingwei.ui.components

import android.content.Context
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Place
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapStatus
import com.baidu.mapapi.map.MapStatusUpdateFactory
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MarkerOptions
import com.baidu.mapapi.map.MyLocationConfiguration
import com.baidu.mapapi.map.MyLocationData
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.map.BitmapDescriptorFactory
import com.example.munidingwei.LocationData

@Composable
fun BaiduMapView(
    currentLocation: LocationData?,
    isSimulating: Boolean,
    modifier: Modifier = Modifier,
    onLocationSelected: ((Double, Double) -> Unit)? = null
) {
    val context = LocalContext.current
    var mapView by remember { mutableStateOf<MapView?>(null) }
    var selectedLocation by remember { mutableStateOf<LatLng?>(null) }
    var isDragging by remember { mutableStateOf(false) }
    var centerLocation by remember { mutableStateOf<LatLng?>(null) }
    
    // 默认位置（北京天安门）
    val defaultLatLng = LatLng(39.9042, 116.4074)
    
    DisposableEffect(Unit) {
        onDispose {
            mapView?.onDestroy()
        }
    }
    
    Box(modifier = modifier) {
        AndroidView(
            factory = { ctx ->
                MapView(ctx).apply {
                    mapView = this
                    
                    // 配置地图
                    map.apply {
                        // 设置地图类型
                        mapType = BaiduMap.MAP_TYPE_NORMAL
                        
                        // 启用定位图层
                        isMyLocationEnabled = !isSimulating
                        
                        // 设置定位图层配置
                        setMyLocationConfiguration(
                            MyLocationConfiguration(
                                MyLocationConfiguration.LocationMode.NORMAL,
                                true,
                                null
                            )
                        )
                        
                        // 添加地图点击监听器
                        setOnMapClickListener(object : BaiduMap.OnMapClickListener {
                            override fun onMapClick(latLng: LatLng) {
                                // 当用户点击地图时，保存选中的位置并回调
                                selectedLocation = latLng
                                onLocationSelected?.invoke(latLng.latitude, latLng.longitude)
                            }
                            
                            override fun onMapPoiClick(mapPoi: com.baidu.mapapi.map.MapPoi) {
                                // POI点击事件 - 也可以触发位置选择
                                val latLng = mapPoi.position
                                selectedLocation = latLng
                                onLocationSelected?.invoke(latLng.latitude, latLng.longitude)
                            }
                        })
                        
                        // 添加地图状态改变监听器（用于拖动）
                        setOnMapStatusChangeListener(object : BaiduMap.OnMapStatusChangeListener {
                            override fun onMapStatusChangeStart(status: MapStatus?) {
                                // 地图开始移动
                                isDragging = true
                            }
                            
                            override fun onMapStatusChangeStart(status: MapStatus?, reason: Int) {
                                // 地图开始移动
                                isDragging = true
                            }
                            
                            override fun onMapStatusChange(status: MapStatus?) {
                                // 地图移动中 - 更新中心点
                                status?.target?.let {
                                    centerLocation = it
                                }
                            }
                            
                            override fun onMapStatusChangeFinish(status: MapStatus?) {
                                // 地图停止移动
                                isDragging = false
                                // 获取地图中心点作为选中位置
                                status?.target?.let { center ->
                                    centerLocation = center
                                }
                            }
                        })
                        
                        // 设置初始位置
                        val initialLocation = currentLocation?.let {
                            LatLng(it.latitude, it.longitude)
                        } ?: defaultLatLng
                        
                        val mapStatus = MapStatus.Builder()
                            .target(initialLocation)
                            .zoom(15f)
                            .build()
                        
                        setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus))
                    }
                }
            },
            update = { view ->
                // 清除旧标记
                view.map.clear()
                
                // 显示当前位置或模拟位置
                currentLocation?.let { location ->
                    val latLng = LatLng(location.latitude, location.longitude)
                    
                    // 移动地图中心到当前位置
                    val newMapStatus = MapStatus.Builder()
                        .target(latLng)
                        .zoom(15f)
                        .build()
                    view.map.animateMapStatus(MapStatusUpdateFactory.newMapStatus(newMapStatus))
                    
                    // 添加位置标记
                    val marker = MarkerOptions()
                        .position(latLng)
                        .title(if (isSimulating) "模拟位置" else "当前位置")
                        .icon(BitmapDescriptorFactory.fromResource(android.R.drawable.ic_menu_mylocation))
                    view.map.addOverlay(marker)
                    
                    // 更新定位数据
                    if (!isSimulating) {
                        val myLocationData = MyLocationData.Builder()
                            .accuracy(location.accuracy)
                            .latitude(location.latitude)
                            .longitude(location.longitude)
                            .build()
                        view.map.setMyLocationData(myLocationData)
                    }
                }
                
                // 如果有选中的位置，显示一个不同颜色的标记
                selectedLocation?.let { selected ->
                    val selectedMarker = MarkerOptions()
                        .position(selected)
                        .title("点击选择的位置")
                        .icon(BitmapDescriptorFactory.fromResource(android.R.drawable.ic_menu_compass))
                    view.map.addOverlay(selectedMarker)
                }
            },
            modifier = Modifier.fillMaxSize()
        )
        
        // 状态指示器
        Card(
            modifier = Modifier
                .padding(16.dp)
                .align(Alignment.TopEnd),
            elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
        ) {
            Row(
                modifier = Modifier.padding(8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    color = if (isSimulating) 
                        MaterialTheme.colorScheme.primary 
                    else 
                        MaterialTheme.colorScheme.secondary,
                    shape = MaterialTheme.shapes.small
                ) {
                    Text(
                        text = if (isSimulating) "模拟中" else "真实位置",
                        modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                        style = MaterialTheme.typography.labelSmall,
                        color = if (isSimulating) 
                            MaterialTheme.colorScheme.onPrimary 
                        else 
                            MaterialTheme.colorScheme.onSecondary
                    )
                }
            }
        }
        
        // 地图中心标记（拖动时显示）
        if (isDragging || centerLocation != null) {
            // 中心点标记图标
            Icon(
                imageVector = androidx.compose.material.icons.Icons.Default.Place,
                contentDescription = "中心标记",
                modifier = Modifier
                    .size(48.dp)
                    .align(Alignment.Center)
                    .offset(y = (-24).dp), // 向上偏移，让底部对准中心
                tint = MaterialTheme.colorScheme.error
            )
        }
        
        // 底部操作区
        if (onLocationSelected != null) {
            Column(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .padding(16.dp),
                horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 确认选择按钮（拖动后显示）
                if (centerLocation != null && !isDragging) {
                    Button(
                        onClick = {
                            centerLocation?.let {
                                selectedLocation = it
                                onLocationSelected.invoke(it.latitude, it.longitude)
                                centerLocation = null // 清除中心点
                            }
                        },
                        colors = ButtonDefaults.buttonColors(
                            containerColor = MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Icon(
                            imageVector = androidx.compose.material.icons.Icons.Default.Check,
                            contentDescription = "确认",
                            modifier = Modifier.size(20.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("设置为模拟位置")
                    }
                }
                
                // 提示卡片
                Card(
                    elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(12.dp),
                        horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = if (isDragging) {
                                "🖐️ 拖动地图选择位置"
                            } else if (centerLocation != null) {
                                "✅ 点击上方按钮确认"
                            } else {
                                "💡 点击或拖动地图选择位置"
                            },
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                        
                        // 显示中心点坐标
                        centerLocation?.let {
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "📍 ${String.format("%.6f", it.latitude)}, ${String.format("%.6f", it.longitude)}",
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.primary
                            )
                        }
                        
                        // 显示已选择的位置
                        if (centerLocation == null) {
                            selectedLocation?.let {
                                Spacer(modifier = Modifier.height(4.dp))
                                Text(
                                    text = "当前: ${String.format("%.6f", it.latitude)}, ${String.format("%.6f", it.longitude)}",
                                    style = MaterialTheme.typography.labelSmall,
                                    color = MaterialTheme.colorScheme.secondary
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}
